const { MongoClient, ObjectID } = require("mongodb");

const client = new MongoClient("mongodb://localhost:27017", {
  useUnifiedTopology: true,
});

// 开启连接
async function run() {
  try {
    // 开始连接
    await client.connect();
    const db = client.db("hello");
    const inventoryCollection = db.collection("inventory");
    // 创建文档
    // const ret = await inventoryCollection.insertOne({
    //   a: 1,
    //   b: 2,
    //   c: true,
    //   d: [1, 2, 3],
    // });

    // 查询文档
    // const ret = await inventoryCollection.find({ item: "notebook" });
    // console.log(await ret.toArray());
    // const ret = await inventoryCollection.findOne({ item: "notebook" });
    // console.log(ret);

    // 删除文档
    /* const ret = await inventoryCollection.deleteOne({
      _id: ObjectID("66a641219b231548acd097a5"),
    });
    console.log(ret); */

    // 更新文档
    const ret = await inventoryCollection.updateOne(
      { _id: ObjectID("66a64130a7507531dcd25bde") },
      { $set: { qty: 100 } }
    );

    console.log(ret);
  } catch (err) {
    console.log(err);
  } finally {
    // 关闭连接
    await client.close();
  }
}

run();
